package com.seestech.sell.common.threads;

import com.seestech.sell.common.config.ApplicationConfig;
import com.seestech.sell.common.config.SpringUtil;
import com.seestech.sell.common.utils.Constants;
import com.seestech.sell.common.utils.DateUtils;
import com.seestech.sell.common.utils.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;



/**
 * Created by idiot on 2017/8/29.
 */
public class LogFileThread implements Runnable {
    private static Logger logger = LoggerFactory.getLogger(LogFileThread.class);

    public static List<String> pool = new ArrayList<>();

    private ApplicationConfig applicationConfig = null;

    //添加数据
    public static void addLogFile(String message){
        synchronized (pool){
            pool.add(pool.size(), message);
            pool.notifyAll();
        }
    }

    @Override
    public void run(){
        while (true){
            if(SpringUtil.getContext() == null){
                try {
                    Thread.currentThread().sleep(1000);
                } catch (InterruptedException e) {
                    logger.error("写入日志文件===>>异常信息==>"+e.getMessage());
                    Thread.currentThread().interrupt();
                }
                continue;
            }
            if(applicationConfig == null)
                applicationConfig = (ApplicationConfig) SpringUtil.getBean("ApplicationConfig");
            String message;
            synchronized (pool){
                while (pool.isEmpty()){
                    logger.info("写入日志文件=====>>>>【开始】");
                    try {
                        pool.wait();
                        Thread.currentThread().sleep(1000 * 10l);
                    } catch (InterruptedException e) {
                        logger.error(e.getMessage(), e);
                        Thread.currentThread().interrupt();
                    }
                }
                message = pool.remove(0);
                logger.info("message======>>>>"+message);
            }
            //数据不为空时
            if(message != null && !"".equals(message)){
                //写入文件
                String fileName = DateUtils.formatDatetime(new Date(), DateUtils.SDF_YM) + ".txt";
                //根据日志的名称  生成对应的文件
                if (message.startsWith("Report")){
                    fileName = "Report-"+fileName;
                }else if (message.startsWith("Log")){
                    fileName = "Log-"+fileName;
                }
                String time = DateUtils.formatDatetime(new Date(), DateUtils.SIMPLE_DATE_HOURS_PATTERN);
                String filePath = FileUtils.getWindowsPath(FileUtils.addPathSeparate(applicationConfig.getBaseDirectory(), Constants.Regular.logs, fileName));
                logger.debug("文件存储目录===="+filePath);
                FileUtils.generateIniFile(filePath, time+"===>>"+message, true);
            }
        }
    }
}
